/*
Work in this file belongs to COMMUNICATION group. 
Other groups are not allowed to make changes on this file. 

During development, you can use your own test code that
includes your own setup() and loop() functions but they 
should not be included when you are submitting your changes. 
*/

/* reads a message */
boolean coReceive(struct MESSAGE *mess) {
/* incoming message format :
* { dst|src|len|cmd|params }
*/    
    byte temp = 0x00;
    byte tempLen = 0x00;
    byte buff[3];

    while ( Serial.available() > 0 ) {
        temp = Serial.read();

        if ( MY_ID != temp ){ /* cleaning buffer for unrelated message */
            temp = Serial.read(); // src
            tempLen = Serial.read(); // len
            temp = Serial.read(); // cmd
            for(byte i = 0; i < tempLen-1; i++){                
                temp = Serial.read(); // params
            }
        }else{
            mess->dest = temp;
            Serial.readBytes((char*) buff, 3);
            mess->src = buff[0];
            mess->len = buff[1];    
            mess->cmd = buff[2];
            delay(10);
            if (mess->len > 1 ){
                Serial.readBytes((char*) mess->params, (mess->len - 1));
            }            
            return true;
        }
    } //end of while
    return false;
}

//sends packets in iyte-prt protocol format
void coSend(byte cmd, char *params) {
  byte len;

  //whether there are extra params or not  
  if(params == NULL) {
    len = 1;                               //only the command's length
  } else {
    len = strlen(params) + 1;              //get the lenght of params and add 1 for command
  }

  byte bytes_sent[len+3];                 //keep header and data in a byte array
  
  //header information
  bytes_sent[0] = SERVER_ID;
  bytes_sent[1] = MY_ID;
  bytes_sent[2] = len;

  //command
  bytes_sent[3] = cmd;

  //params
  for(byte i = 0; i < len-1; i++) {
    bytes_sent[i+4] = (byte) params[i];
  }

  //send the byte array to xbee
  Serial.write(bytes_sent, len+3);  
}
